package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberDao;
import com.itheima.health.service.MemberService;
import com.itheima.health.vo.EChartsReportVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * @author 施子安
 * @version 1.0
 * @date 2023/4/27 13:06
 * @Description 会员数据业务处理层
 */
@Repository
@Slf4j
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;

    /**
     * 饼状图 查询一年内每个月份会员数量
     *
     * @return
     */
    @Override
    public EChartsReportVo getMemberReport() {
        //方法一 通过sql语句查询 不需要做格式转换
//        List<Map<String, Integer>> list = memberDao.getMemberReport();

//        log.info("list:{}", list.get(list.size() - 1));
        //公共部分
        EChartsReportVo reportVo = new EChartsReportVo();
        //定义月份变量
        ArrayList<String> months = new ArrayList<>();
        //定义月份数量
        ArrayList<Integer> monthCount = new ArrayList<>();
        //方法一
        //循环封装数据
//        list.forEach(item -> {
//            months.add(String.valueOf(item.get("month")));
//            monthCount.add(Integer.parseInt(String.valueOf(item.get("count"))));
//        });
        //方法二 自定义日期封装
        //获取日期对象
        Calendar calendar = Calendar.getInstance();
        //构造月份
        calendar.add(Calendar.MONDAY,-11);
        DateFormat df = new SimpleDateFormat("yyyy.MM");
        for (int i = 0; i <12 ; i++) {
            months.add(df.format(calendar.getTime()));
            calendar.add(Calendar.MONTH,1);
        }
        //循环赋值月份会员数量
        for (String month : months) {

            String date_str = month + ".10";
            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
            try {
                c.setTime(sdf.parse(date_str));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            c.add(Calendar.MONTH, 1);
            c.set(Calendar.DAY_OF_MONTH, 0);
            // 获取当月最后一天
            String lastDayOfMonth = sdf.format(c.getTime());
            Long count = memberDao.countByRegTimeBefore(lastDayOfMonth);
            //像集合中添加每月会员数据
            monthCount.add(count.intValue());
        }


        //公共部分
        log.info("月份信息：{}", months);
        log.info("数量：{}", monthCount);
        //赋值
        reportVo.setMonths(months);
        reportVo.setMemberCount(monthCount);
        return reportVo;
    }
}
